<?php

namespace app\common\model\banxi\learn;

use app\common\enums\AccountTypeEnum;
use app\common\enums\MemorizeModeEnum;
use app\common\model\common\BaseModel;
use think\model\concern\SoftDelete;

/**
 * 单词识记记录
 */
class LearnWordMemorizeRecord extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_learn_word_memorize_record';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'accountTypeCn',
        'memorizeModeCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'courseId' => 'string',
        'studentId' => 'string',
        'trainerId' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];


    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getAccountTypeCnAttr($value, $data)
    {
        $value = $value ?: ($data['accountType'] ?? '');
        return (new AccountTypeEnum())->getDescription($value) ?? '';
    }

    public function getMemorizeModeCnAttr($value, $data)
    {
        $value = $value ?: ($data['memorizeMode'] ?? '');
        return (new MemorizeModeEnum())->getDescription($value) ?? '';
    }
    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------


    /*
     * 查询学员学过的单词数量
     * */
    public static function countByStudent(int $student_id, int $memorize_mode, int $memorize_level): string|int
    {
        return self::where(['studentId' => $student_id, 'memorizeMode' => MemorizeModeEnum::E1])
            ->whereBetween('memorizeLevel', [$memorize_mode, $memorize_level])
            ->distinct('word')
            ->count();
    }

    /**
     * 根据课程和账户信息查询单词记忆记录
     * @param string $accountId 账户ID
     * @param string $accountType 账户类型
     * @param int $courseId 课程ID
     * @param int|null $beginLevel 起始记忆等级
     * @param int|null $endLevel 结束记忆等级
     * @param string $learnMeans 学习方式
     * @param string $memorizeMode 记忆模式
     * @param bool $reviewIs 是否复习
     * @return array 单词记忆记录列表
     */
    public function listByCourseAndAccount($accountId, $accountType, $courseId,
                                           $beginLevel, $endLevel, $learnMeans,
                                           $memorizeMode, $reviewIs)
    {
        // 构建查询条件
        $db = $this->alias('r')
            ->where('r.accountId', $accountId)
            ->where('r.accountType', $accountType)
            ->where('r.memorizeMode', $memorizeMode)
            ->where('r.courseId', $courseId);

        // 如果开始和结束等级都不为空，则添加等级范围条件
        if ($beginLevel && $endLevel) {
            $db->whereBetween('r.memorizeLevel', [$beginLevel, $endLevel]);
        }

        // 如果学习方式不为空，则添加学习方式条件
        if ($learnMeans) {
            $db->where('r.learnMeans', $learnMeans);
        }

        // 如果是复习查询，则添加复习时间条件
        if ($reviewIs) {
            $today = date('Y-m-d');
            $db->where(function ($query) use ($today) {
                $query->where('r.reviewTime', '<', $today)
                    ->whereOr('r.reviewTime', 'null');
            });
        }

        // 关联词库表查询
        $db->join('banxi_lexicon l', 'l.courseId = r.courseId AND l.word = r.word');

        // 执行查询并返回结果
        return $db->select();
    }


    /**
     * 提交学习识记记录
     */
    public function submitLearnRememberWordRecord($accountId, $accountType, $learnMeans, $memorizeMode, $submitLearn, $learnWordMemorizeRecordList)
    {
        $courseId = $submitLearn['courseId'];
        $learnWordList = $submitLearn['learnWordList'];
        $nowTime = time();

        $saveList = [];
        $updateList = [];
        //        Log::info('新增记录studentId:'.($accountType == AccountTypeEnum::STUDENT) ? $accountId : null);
        foreach ($learnWordList as $learnWord) {
            $word = $learnWord['word'];
            $learnWordMemorizeRecord = null;

            // 查找对应的记录
            foreach ($learnWordMemorizeRecordList as $record) {
                if ($record['word'] == $word) {
                    $learnWordMemorizeRecord = $record;
                    break;
                }
            }

            if ($learnWordMemorizeRecord == null) {

                // 新增记录
                $memorizeLevel = $learnWord['result'] ? 1 : 0;
                $saveList[] = [
                    'courseId' => $courseId,
                    'accountId' => $accountId,
                    'accountType' => $accountType,
                    'word' => $word,
                    'newTime' => date('Y-m-d H:i:s', $nowTime),
                    'memorizeLevel' => $memorizeLevel,
                    'learnMeans' => $learnMeans,
                    'memorizeMode' => $memorizeMode,
                    'trainerId' => ($accountType == AccountTypeEnum::TRAINER) ? $accountId : null,
                    'studentId' => ($accountType == AccountTypeEnum::STUDENT) ? $accountId : null,
                    'createTime' => $nowTime,
                    'updateTime' => $nowTime
                ];

            } else {
                // 修改记录
                $memorizeLevel = $learnWord['result'] ? $learnWordMemorizeRecord['memorizeLevel'] + 1 : 0;
                if ($learnWordMemorizeRecord['memorizeLevel'] >= 7) {
                    $memorizeLevel = 7;
                }

                $updateList[] = [
                    'id' => $learnWordMemorizeRecord['id'],
                    'reviewTime' => date('Y-m-d H:i:s', $nowTime),
                    'memorizeLevel' => $memorizeLevel,
                    'learnMeans' => $learnMeans,
                    'updateTime' => $nowTime
                ];
            }
        }

        // 批量插入新记录
        if (!empty($saveList)) {
            $this->insertAll($saveList);
        }

        // 批量更新记录
        if (!empty($updateList)) {
            foreach ($updateList as $update) {
                $this->update($update, ['id' => $update['id']]);
            }
        }

        // 统计正确和错误数量
        $rightNum = 0;
        $errorNum = 0;
        foreach ($learnWordList as $learnWord) {
            if ($learnWord['result']) {
                $rightNum++;
            } else {
                $errorNum++;
            }
        }

        return [
            'rightNum' => $rightNum,
            'errorNum' => $errorNum
        ];
    }


    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------


}